'''
Description: 
Author: Zilu
Date: 2021-11-11 10:48:44
Version: 
LastEditTime: 2021-11-11 11:43:33
LastEditors: Zilu
'''

# 获取当前时间
from datetime import datetime, time
now = datetime.now()
print(now)

# 指定某个日期
d = datetime(2015,9,12,20,0)
print(d)

# timestamp UTC 1970-1-1 00:00:00 称为 epoch time
# 转换成timestamp，整数位是秒
d.timestamp()

# 使用 fromtimestamp 转换成datetime
t = d.timestamp()
d1 = datetime.fromtimestamp(t)
type(d1)
print(d1)

# 转换得到的时间是本地操作系统设定的时区，也可以转换得到utc的时间
print(datetime.utcfromtimestamp(t))

# 可以使用格式化字符串转换成时间，
# 具体说明见https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
cday = datetime.strptime('2015-06-01 18:19:59', '%Y-%m-%d %H:%M:%S')
print(cday)
cday
# 转换后的时间没有时区信息

# 用strftime将datetime的时间转换成指定格式的字符串
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))

# datetime 的加减，使用timedelta类，并结合普通的+-运算
from datetime import timedelta
now
now + timedelta(hours=12)
now - timedelta(days=1,hours=3)
now + timedelta(days=3)

# 可以给datetime设定时区，需要使用timezone类
from datetime import timezone
tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00
now = datetime.now()
now
dt = now.replace(tzinfo=tz_utc_8)
dt

# 时区转换：先通过utcnow()得到当前时间，再转换
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print(bj_dt)
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt)
tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))      # 即使是用北京时间，时区计算仍是以UTC为准
print(tokyo_dt2)

now = datetime.now()
print(now.tzinfo)
print(now)
t = now.timestamp()
t
print(datetime.fromtimestamp(t))
print(datetime.utcfromtimestamp(t))

# 不指定tzinfo的情况下，时区信息是None，但是转换成timestamp的时候默认是本地时区时间
d = datetime(1970,1,1,10,0,tzinfo=timezone.utc)
print(d.tzinfo)
dt = d.timestamp()
dt
print(datetime.fromtimestamp(dt))
print(datetime.utcfromtimestamp(dt))

# 练习：假设你获取了用户输入的日期和时间如2015-1-21 9:01:30，
# 以及一个时区信息如UTC+5:00，均是str，请编写一个函数将其转换为timestamp：
import re
from datetime import datetime,timedelta,timezone
def to_timestamp(dt_str,tz_str):
    m = re.match(r'UTC([\+\-][0-1]?[0-9]|2[0-3]):([0-5]?[0-9])', tz_str)
    if m:
        dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S').replace(
            tzinfo=timezone(timedelta(hours=int(m[1]),minutes=int(m[2]))))
        return dt.timestamp()
    else:
        print('format error!')

t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00')
assert t1 == 1433121030.0, t1

t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00')
assert t2 == 1433121030.0, t2

print('ok')
